/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mscs.client.goods.logic;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import mscs.data.pojo.Goods;
import mscs.data.pojo.Operation;
import mscs.data.pojo.Person;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;

/**
 *
 * @author Usbuild
 */
public class GoodsUtilAOP {
    Enhancer enhancer = new Enhancer();
    Person person;
    public GoodsUtilAOP(Person person) {
        this.person = person;
        enhancer.setSuperclass(GoodsUtil.class);
        Interceptor interceptor = new Interceptor();
        interceptor.setGoodsUtil(new GoodsUtil());
        interceptor.setPerson(person);
        enhancer.setCallback(interceptor);
    }
    public GoodsUtil create() {
        return (GoodsUtil)enhancer.create();
    }
}
class Interceptor implements InvocationHandler{
    GoodsUtil goodsUtil;
    Operation operation = new Operation();
    Person person;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
    

    public void setGoodsUtil(GoodsUtil goodsUtil) {
        this.goodsUtil = goodsUtil;
    }
    
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
        if("commitCacheList".equals(method.getName())) {
            setNum(goodsUtil.getCacheList());
            saveTheOperation(new InOperationUtil(), goodsUtil.getCacheList());
        }
        else if("endOut".equals(method.getName()))
            saveTheOperation(new OutOperationUtil(), goodsUtil.getOutGoodsList());
        return method.invoke(goodsUtil, args);
    }
    private void saveTheOperation(OperationUtil operationUtil, ArrayList list) {
        operation.setGoodsList(list);
        operation.setId((int)new Date().getTime());
        operation.setOperator(person);//TODO: 添加操作者信息
        operation.setDate(new Date());
        operationUtil.add(operation);
    }
    private void setNum(ArrayList<Goods> goodsList) {
        Hashtable<String, Integer> goodsNum = new Hashtable<String, Integer>();
        for(Goods goods : goodsList) {
           Goods preGoods = goodsUtil.queryByExample(goods);
           goodsNum.put(preGoods.getId(), preGoods.getNum());
        }
        operation.setGoodsNum(goodsNum);
    }
}
